package exercise.service;


import exercise.dao.RoleDao;
import exercise.dao.UserDao;
import exercise.domain.Role;
import exercise.domain.User;

import java.util.List;

public class UserServiceImpl implements UserService {
    //注入userDao
    private UserDao userDao;

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    private RoleDao roleDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User login(String userName, String password) {
        try{
            User user=userDao.findByUserNameAndPassword(userName,password);
            return user;
        }catch(Exception e){
            return null;
        }


    }

    @Override
    public void del(Long userId) {
        //删除关系表
        userDao.delUserRoleRel(userId);
        //删除user表
        userDao.delUser(userId);
    }

    @Override
    public void save(User user, Long[] roleIds) {
        //1.向sys_user表存数据
        Long userId=userDao.save(user);
        //2.向sys_user_role表存数据
        userDao.saveUserRoleRel(userId,roleIds);
    }

    @Override
    public List<User> list() {
        List<User> users = userDao.finAll();
        //封装userList则每一个user的role数据
        for(User user: users){
            Long id = user.getId();
            //将ID作为参数，查询当前ID对应的role集合
            List<Role> roles=roleDao.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return users;
    }
}
